package com.sun.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class test02 {
    public static void main(String[] args) throws InterruptedException {
//        int[] arr = {1,4,5,7};
//        int index = getIndex(arr, 1);
//        System.out.println(index);
        Pepole pepole = new Pepole();
        new Thread(()->{
            pepole.outA();
        }).start();
        new Thread(()->{
            pepole.outB();
        }).start();
        new Thread(()->{
            pepole.outC();
        }).start();

    }
    public static int getIndex(int[] arr,int dem){
        List list = new ArrayList();
        for (int i : arr) {
            list.add(i);
        }
        int index = list.indexOf(dem);
        if (index < 0){
            list.add(dem);
            Collections.sort(list);
            index = list.indexOf(dem);
        }
        return index;
    }
}

class Pepole{
    private final static Lock lock = new ReentrantLock();
    private final static Condition c1 = lock.newCondition();
    private final static Condition c2 = lock.newCondition();
    private final static Condition c3 = lock.newCondition();
    private  static String str = "A";
    public void outA(){
        try {
            lock.lock();
            while (!str.equals("A")){
                c1.await();
            }

            str = "B";
            System.out.println("A");
            c2.signal();
        } catch (InterruptedException e) {
                e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
    public void outB(){
        try {
            lock.lock();
            while (!str.equals("B")){
                c2.await();
            }

            str = "C";
            System.out.println("B");
            c3.signal();
        } catch (InterruptedException e) {
                e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
    public void outC(){
        try {
            lock.lock();
            while (!str.equals("C")){
                c3.await();
            }

            str = "A";
            System.out.println("C");
            c1.signal();
        } catch (InterruptedException e) {
                e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
